The Browser Object Model (BOM) allows JavaScript to interact with the browser. Here are some common BOM objects and methods:
The window
object represents the browser window and provides methods to control it:
console.log(window.innerWidth); // Width of the window's content area
console.log(window.innerHeight); // Height of the window's content area
// Open a new window
const newWindow = window.open('https://nitinmaurya67.github.io/MyClass', '_blank', 'width=600,height=400');
// Close the new window
setTimeout(() => newWindow.close(), 3000);
// Display an alert
window.alert(' setTimeout !! ');
The navigator
object contains information about the browser and the user's environment:
console.log(navigator.userAgent); // User agent string
console.log(navigator.language); // Browser language
console.log(navigator.platform); // Operating system
// Check if cookies are enabled
if (navigator.cookieEnabled) {
console.log('Cookies are enabled');
} else {
console.log('Cookies are disabled');
}
The location
object contains information about the current URL and provides methods to manipulate
it:
console.log(location.href); // Full URL
console.log(location.hostname); // Domain name
console.log(location.pathname); // Path of the URL
console.log(location.protocol); // Protocol (http: or https:)
location.href = 'https://www.example.com'; // Redirect to a new URL
location.reload(); // Reload the current page
The history
object allows manipulation of the browser session history:
history.back(); // Go back to the previous page
history.forward(); // Go forward to the next page
history.go(-2); // Go back two pages
// Add a new entry to the history stack
history.pushState({ page: 1 }, 'title 1', '?page=1');
// Replace the current entry in the history stack
history.replaceState({ page: 2 }, 'title 2', '?page=2');
The screen
object contains information about the user's screen:
console.log(screen.width); // Screen width
console.log(screen.height); // Screen height
console.log(screen.availWidth); // Available screen width
console.log(screen.availHeight); // Available screen height